package com.ruoyi.common.sms.entinfo;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.ruoyi.common.sms.core.SmsEnum;
import com.ruoyi.common.sms.core.SmsProperties;
import com.ruoyi.common.sms.core.SmsResult;
import com.ruoyi.common.sms.core.SmsTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName：EntinfoSmsTemplate
 * Package：com.ruoyi.common.sms.entinfo
 * Description：
 *
 * @Author：fpy
 * @Create：2025/5/6 - 14:16
 * @Version：v1.0
 */
@Slf4j
@RequiredArgsConstructor
public class EntinfoSmsTemplate implements SmsTemplate {

    private final SmsProperties smsProperties;

    private final EntinfoSmsProperties entinfoSmsProperties;

    @Override
    public String channel() {
        return smsProperties.getType();
    }

    /**
     * entinfo短信通道实际发送代码
     *
     * @param: template
     * @param: phone
     * @param: content
     * @return: com.ruoyi.common.sms.core.SmsResult
     * @author: fpy
     * @date: 2025/5/6 14:30
    **/
    @Override
    public SmsResult message(SmsEnum template, String phone, String... content) {
        final Thread thread = Thread.currentThread();
        log.info("SMS线程【{}】,SMS通道【{}】,接受电话【{}】,发送内容【{}】", Thread.currentThread(), channel(), phone, content);

        if (template == null) {
            return new SmsResult(false, "非法短信模板");
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sn", entinfoSmsProperties.getAccount());
        paramMap.put("pwd", getPwd());
        paramMap.put("mobile", phone);
        final String format = String.format(template.getContent(channel()), content);
        paramMap.put("content", URLEncodeUtil.encode(format, StandardCharsets.UTF_8));

        HttpResponse httpResponse = HttpRequest.post(entinfoSmsProperties.getUrl())
                .header(Header.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .form(paramMap)
                .timeout(10000)
                .execute();

        if (!httpResponse.isOk()) {
            return new SmsResult(false, httpResponse.body());
        }

        final String body = httpResponse.body();
        // 错误码的特征是负数，因此以“-”开头
        SmsResult smsResult = new SmsResult(!StrUtil.startWithIgnoreCase(body, "-"), body);
        log.info("SMS线程【{}】,结果【{}】", thread, smsResult);
        return smsResult;
    }

    /**
     * 密码处理
     *
     * @param:
     * @return: java.lang.String
     * @author: fpy
     * @date: 2025/5/6 14:44
    **/
    private String getPwd() {
        String data = entinfoSmsProperties.getAccount() + entinfoSmsProperties.getPassword();
        return SecureUtil.md5(data).toUpperCase();
    }
}
